package com.scriptback.controller;

import com.scriptback.dto.common.ApiResponse;
import com.scriptback.dto.common.PageResponse;
import com.scriptback.dto.project.ProjectRequestDTO;
import com.scriptback.dto.project.ProjectResponseDTO;
import com.scriptback.entity.Project;
import com.scriptback.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目管理控制器
 */
@Controller
@RequestMapping("/projects")
@Validated
public class ProjectController {


    @Autowired
    private ProjectService projectService;


    @PostMapping
    @ResponseBody
    public ApiResponse<ProjectResponseDTO> createProject(@RequestBody ProjectRequestDTO request){

        try{
            Project project = projectService.createProject
                    (request.getProjectName(), request.getProjectDescription());

            ProjectResponseDTO projectResponseDTO = ProjectResponseDTO.fromEntity(project);

            return ApiResponse.success("成功创建", projectResponseDTO);

        }catch (Exception e){

            return ApiResponse.error("创建项目失败: " + e.getMessage());

        }

    }

    @GetMapping
    @ResponseBody
    public ApiResponse<PageResponse<ProjectResponseDTO>> getAllProjects(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        try {
            PageRequest pageRequest = PageRequest.of(page, size);
            Page<Project> projectPage = projectService.getAllProjects(pageRequest);

            List<ProjectResponseDTO> content = projectPage.getContent().stream()
                    .map(ProjectResponseDTO::fromEntity)
                    .collect(Collectors.toList());

            // 创建分页响应对象
            PageResponse<ProjectResponseDTO> pageResponse = new PageResponse<>(
                    content,
                    projectPage.getNumber(),
                    projectPage.getSize(),
                    projectPage.getTotalElements(),
                    projectPage.getTotalPages(),
                    projectPage.isFirst(),
                    projectPage.isLast()
            );

            return ApiResponse.success("获取项目成功", pageResponse);

        } catch (Exception e) {
            return ApiResponse.error("获取项目失败: " + e.getMessage());
        }
    }


    @GetMapping("/search")
    @ResponseBody
    public ApiResponse<PageResponse<ProjectResponseDTO>> searchProjectsByName(
            @RequestParam String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size){

        try{
            PageRequest pageRequest = PageRequest.of(page, size);

            Page<Project> projects = projectService.searchProjectsByName(name, pageRequest);

            List<ProjectResponseDTO> content = projects.getContent().stream()
                    .map(ProjectResponseDTO::fromEntity)
                    .collect(Collectors.toList());

            PageResponse<ProjectResponseDTO> projectResponseDTOPageResponse = new PageResponse<>(
                    content,
                    projects.getNumber(),
                    projects.getSize(),
                    projects.getTotalElements(),
                    projects.getTotalPages(),
                    projects.isFirst(),
                    projects.isLast()
            );

            return ApiResponse.success("成功通过项目名称查询到信息", projectResponseDTOPageResponse);
        }catch (Exception e){

            return ApiResponse.error("通过项目名称查询信息失败: " + e.getMessage());
        }

    }

    @GetMapping("/{id}")
    @ResponseBody
    public ApiResponse<ProjectResponseDTO> getProjectById(@PathVariable String id){
        try{

            Project projectById = projectService.getProjectById(id);
            ProjectResponseDTO projectResponseDTO = ProjectResponseDTO.fromEntity(projectById);
            return ApiResponse.success("通过ID，成功获取到项目", projectResponseDTO);
        }catch (Exception e){
            return ApiResponse.error("通过ID，没有成功获取到项目: " + e.getMessage());
        }

    }

    @PostMapping("/{id}/update")
    @ResponseBody
    public ApiResponse<ProjectResponseDTO>updateProject(@PathVariable String id,
                                                        @RequestBody ProjectRequestDTO request){

        try{

            Project project = projectService.updateProject(id, request.getProjectName(), request.getProjectDescription());
            ProjectResponseDTO projectResponseDTO = ProjectResponseDTO.fromEntity(project);
            return ApiResponse.success("更新项目信息成功: ", projectResponseDTO);

        }catch (Exception e){
            return ApiResponse.error("更新项目信息失败: " + e.getMessage());
        }


    }

    @PostMapping("/{id}/delete")
    @ResponseBody
    public ApiResponse<Void>deleteProject(@PathVariable String id){

        try{
            projectService.deleteProject(id);
            return ApiResponse.success("删除成功", null);

        }catch (Exception e) {

            return ApiResponse.error("删除项目失败: " + e.getMessage());

        }

    }




}
